package com.uziot.bucket.common.recursivetask;

import cn.hutool.core.util.CreditCodeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;


/**
 * @author shidt
 * @version V1.0
 * @className RecursiveTaskDemo
 * @date 2019-12-20 08:51:35
 * @description 有返回值的工作窃取算法
 */

@Slf4j
public class RecursiveTaskDemo extends RecursiveTask<List<String>> {

    /**
     * 任务拆分临界点
     */
    private static final Integer MAX_LIMIT = 20;

    private final Integer start;
    private final Integer end;
    private final List<String> urls;

    public RecursiveTaskDemo(Integer start, Integer end, List<String> urls) {
        this.start = start;
        this.end = end;
        this.urls = urls;
    }

    @Override
    protected List<String> compute() {
        //任务足够小（类似递归）
        if ((end - start) < MAX_LIMIT) {
            ArrayList<String> result = new ArrayList<>();
            // 取得任务列表
            List<String> list = urls.subList(start, end);
            // 执行视线范围内的任务
            for (String task : list) {
                String creditCode = CreditCodeUtil.randomCreditCode();
                log.info("正在执行:{},结果：{}", task, creditCode);
                result.add(creditCode);
            }
            return result;
        } else {
            //拆分任务
            int middle = (end + start) / 2;
            RecursiveTaskDemo leftTask = new RecursiveTaskDemo(start, middle, urls);
            RecursiveTaskDemo rightTask = new RecursiveTaskDemo(middle, end, urls);

            //执行任务
            leftTask.fork();
            rightTask.fork();

            //汇总各个分任务节点
            List<String> leftList = leftTask.join();
            List<String> rightList = rightTask.join();
            leftList.addAll(rightList);
            return leftList;
        }
    }


}